package com.example.myadmin.user.controller;

import com.example.myadmin.common.vo.Result;
import com.example.myadmin.user.entity.User;
import com.example.myadmin.user.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    @ResponseBody
    public Result<Object> login(User param, HttpSession session, HttpServletRequest request,
                        //验证码参数
                        @RequestParam("captcha") String captcha){
        if (!CaptchaUtil.ver(captcha, request)) {
            return Result.fail("验证码错误");
        }
        User login = userService.login(param);
        if (login!=null){
            BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
            //参数一，请求密码   参数二，数据库里加密的值
            //matches为true时前端传来的密码与数据库里的密码相同
            // 由于Sql里不能查询密码，所以login不为空只能证明用户名相同
            boolean matches = bCryptPasswordEncoder.matches(param.getPassword(), login.getPassword());
            if (matches){
                //将用户信息写入session
                login.setPassword(null); //防止密码泄露
                //不采用param的原因：后面取chName时，前端并没有chName的值
                session.setAttribute("userInfo",login);
                return Result.success();
            }
        }
        return Result.fail("用户名或密码错误");
    }
}
